/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.util.StringUtils;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.JsonUtils;
import io.renren.common.validator.AssertUtils;
import io.renren.core.dto.LearnUserScoreDTO;
import io.renren.core.service.LearnUserScoreService;
import io.renren.dao.UserDao;
import io.renren.dto.LoginDTO;
import io.renren.dto.MiniLoginDTO;
import io.renren.entity.TokenEntity;
import io.renren.entity.UserEntity;
import io.renren.service.TokenService;
import io.renren.service.UserService;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.jsoup.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {
    private final TokenService tokenService;
    private static final String APP_ID = "wx1854f07535708b73";
    private static final String APP_SECRET = "4cd8b60e4e72f827d93151e33a565b24";
    private static final String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @Autowired
    private LearnUserScoreService learnUserScoreService;

    @Override
    public UserEntity getByMobile(String mobile) {
        return baseDao.getUserByMobile(mobile);
    }

    @Override
    public UserEntity getUserByUserId(Long userId) {
        return baseDao.getUserByUserId(userId);
    }

    @Override
    public UserEntity getByWxId(String wxId) {
        return baseDao.getUserByWxId(wxId);
    }

    @Override
    public Map<String, Object> login(LoginDTO dto) {
        UserEntity user = getByMobile(dto.getMobile());
        AssertUtils.isNull(user, ErrorCode.ACCOUNT_PASSWORD_ERROR);

        //密码错误
        if (!user.getPassword().equals(DigestUtil.sha256Hex(dto.getPassword()))) {
            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());

        return map;
    }

    @Override
    public Map<String, Object> miniLogin(MiniLoginDTO dto) {
        Map<String, Object> map = new HashMap<>(1);

        String wxId = dto.getWxId();

        // 请求WX
        if (StringUtils.isBlank(wxId)) {
            String result = HttpUtil.get(String.format(WX_URL, APP_ID, APP_SECRET, dto.getCode()));
            WXResult wxResult = JsonUtils.parseObject(result, WXResult.class);
            if (Objects.nonNull(wxResult) && StringUtils.isNotBlank(wxResult.getOpenid())) {
                wxId = wxResult.getOpenid();
            }
        }

        if (StringUtils.isBlank(wxId)) {
            log.error("登录失败!");
            throw new RuntimeException("登录失败");
        }

        UserEntity user = getByWxId(wxId);
        if (Objects.isNull(user)) {
            user = new UserEntity();
            user.setUsername(UUID.randomUUID().toString().replace("-", ""));
            user.setWxId(wxId);
            user.setMobile("");
            user.setCreateDate(new Date());
            baseDao.insert(user);
        }

        LearnUserScoreDTO userScoreDTO = learnUserScoreService.getByUserId(user.getId());
        if (Objects.isNull(userScoreDTO)) {
            userScoreDTO = new LearnUserScoreDTO();
            userScoreDTO.setUserId(user.getId());
            userScoreDTO.setUserPoint(0);
            userScoreDTO.setUserLearnScore(0);
            userScoreDTO.setCreateDate(new Date());
            userScoreDTO.setUpdateDate(new Date());
            learnUserScoreService.save(userScoreDTO);
        }

        map.put("wxId", user.getWxId());

        return map;
    }

    @Data
    public static class WXResult {
        String openid;
        String session_key;
        String unionid;
        Integer errcode;
        String errmsg;
    }

}